package repository

import (
	"blog/internal/model"
	"context"
)

type ArticleTagRelationRepository interface {
	CreateRelation(ctx context.Context, relation *model.ArticleTagRelation) error
	DeleteRelationsByArticleID(ctx context.Context, articleID uint) error
	GetTagIDsByArticleID(ctx context.Context, articleID uint) ([]uint, error)
	GetArticleIDsByTagID(ctx context.Context, tagID uint, ids *[]uint) error
}

func NewArticleTagRelationRepository(
	repository *Repository,
) ArticleTagRelationRepository {
	return &articleTagRelationRepository{
		Repository: repository,
	}
}

type articleTagRelationRepository struct {
	*Repository
}

func (r *articleTagRelationRepository) GetArticleIDsByTagID(ctx context.Context, tagID uint, ids *[]uint) error {
	return r.DB(ctx).Model(&model.ArticleTagRelation{}).
		Where("tag_id = ?", tagID).
		Pluck("article_id", ids).Error
}

func (r *articleTagRelationRepository) CreateRelation(ctx context.Context, relation *model.ArticleTagRelation) error {
	return r.DB(ctx).Create(relation).Error
}
func (r *articleTagRelationRepository) DeleteRelationsByArticleID(ctx context.Context, articleID uint) error {
	return r.DB(ctx).Where("article_id = ?", articleID).Delete(&model.ArticleTagRelation{}).Error
}

func (r *articleTagRelationRepository) GetTagIDsByArticleID(ctx context.Context, articleID uint) ([]uint, error) {
	var ids []uint
	err := r.DB(ctx).Model(&model.ArticleTagRelation{}).Where("article_id = ?", articleID).Pluck("tag_id", &ids).Error
	if err != nil {
		return nil, err
	}
	return ids, nil
}
